class Solution {
public:
    int countKConstraintSubstrings(string s, int k)
    {
        int ans = 0;
        int cnt1 = 0;
        int cnt2 = 0;
        int left = 0, right = 0;
        int n = s.size();
        while (right < n)
        {
            if (s[right++] == '0') cnt1++;
            else cnt2++;
            while (left < right && (cnt1 > k && cnt2 > k))
            {
                if (s[left] == '0') cnt1--;
                else cnt2--;
                left++;
            }
            ans += right - left;
        }
        return ans;
    }
};